// WebSocket实时数据工具
import { ref, reactive } from 'vue'

class WebSocketManager {
  constructor() {
    this.connections = new Map()
    this.reconnectAttempts = new Map()
    this.maxReconnectAttempts = 5
    this.reconnectInterval = 3000
  }

  /**
   * 创建WebSocket连接
   * @param {string} url WebSocket地址
   * @param {string} key 连接标识
   * @param {Object} options 配置选项
   */
  connect(url, key = 'default', options = {}) {
    const {
      onMessage = () => {},
      onOpen = () => {},
      onClose = () => {},
      onError = () => {},
      autoReconnect = true
    } = options

    if (this.connections.has(key)) {
      this.disconnect(key)
    }

    const ws = new WebSocket(url)
    
    ws.onopen = (event) => {
      console.log(`WebSocket连接已建立: ${key}`)
      this.reconnectAttempts.set(key, 0)
      onOpen(event)
    }

    ws.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data)
        onMessage(data)
      } catch (error) {
        console.error('WebSocket消息解析失败:', error)
        onMessage(event.data)
      }
    }

    ws.onclose = (event) => {
      console.log(`WebSocket连接已关闭: ${key}`)
      this.connections.delete(key)
      onClose(event)

      if (autoReconnect && !event.wasClean) {
        this.attemptReconnect(url, key, options)
      }
    }

    ws.onerror = (event) => {
      console.error(`WebSocket连接错误: ${key}`, event)
      onError(event)
    }

    this.connections.set(key, ws)
    return ws
  }

  /**
   * 尝试重连
   */
  attemptReconnect(url, key, options) {
    const attempts = this.reconnectAttempts.get(key) || 0
    
    if (attempts < this.maxReconnectAttempts) {
      this.reconnectAttempts.set(key, attempts + 1)
      
      setTimeout(() => {
        console.log(`尝试重连WebSocket: ${key} (${attempts + 1}/${this.maxReconnectAttempts})`)
        this.connect(url, key, options)
      }, this.reconnectInterval)
    } else {
      console.error(`WebSocket重连失败，已达到最大重试次数: ${key}`)
    }
  }

  /**
   * 发送消息
   * @param {string} key 连接标识
   * @param {any} data 要发送的数据
   */
  send(key, data) {
    const ws = this.connections.get(key)
    if (ws && ws.readyState === WebSocket.OPEN) {
      ws.send(typeof data === 'string' ? data : JSON.stringify(data))
    } else {
      console.warn(`WebSocket连接不可用: ${key}`)
    }
  }

  /**
   * 断开连接
   * @param {string} key 连接标识
   */
  disconnect(key) {
    const ws = this.connections.get(key)
    if (ws) {
      ws.close()
      this.connections.delete(key)
      this.reconnectAttempts.delete(key)
    }
  }

  /**
   * 断开所有连接
   */
  disconnectAll() {
    this.connections.forEach((ws, key) => {
      this.disconnect(key)
    })
  }

  /**
   * 获取连接状态
   * @param {string} key 连接标识
   */
  getConnectionState(key) {
    const ws = this.connections.get(key)
    if (!ws) return 'CLOSED'
    
    switch (ws.readyState) {
      case WebSocket.CONNECTING: return 'CONNECTING'
      case WebSocket.OPEN: return 'OPEN'
      case WebSocket.CLOSING: return 'CLOSING'
      case WebSocket.CLOSED: return 'CLOSED'
      default: return 'UNKNOWN'
    }
  }
}

// 全局WebSocket管理器实例
const wsManager = new WebSocketManager()

/**
 * 实时数据Hook
 * @param {string} url WebSocket地址
 * @param {string} key 连接标识
 * @param {Object} options 配置选项
 */
export const useRealTimeData = (url, key = 'default', options = {}) => {
  const data = ref(null)
  const connected = ref(false)
  const error = ref(null)

  const connect = () => {
    wsManager.connect(url, key, {
      ...options,
      onMessage: (message) => {
        data.value = message
        if (options.onMessage) {
          options.onMessage(message)
        }
      },
      onOpen: () => {
        connected.value = true
        error.value = null
        if (options.onOpen) {
          options.onOpen()
        }
      },
      onClose: () => {
        connected.value = false
        if (options.onClose) {
          options.onClose()
        }
      },
      onError: (err) => {
        error.value = err
        connected.value = false
        if (options.onError) {
          options.onError(err)
        }
      }
    })
  }

  const disconnect = () => {
    wsManager.disconnect(key)
    connected.value = false
  }

  const send = (message) => {
    wsManager.send(key, message)
  }

  return {
    data,
    connected,
    error,
    connect,
    disconnect,
    send
  }
}

/**
 * 模拟实时数据（用于演示）
 */
export const useMockRealTimeData = (interval = 3000) => {
  const data = reactive({
    onlineUsers: 0,
    realTimeOrders: 0,
    todaySales: 0,
    conversionRate: 0,
    timestamp: Date.now()
  })

  let timer = null

  const start = () => {
    const updateData = () => {
      data.onlineUsers = Math.floor(Math.random() * 1000) + 500
      data.realTimeOrders = Math.floor(Math.random() * 50) + 10
      data.todaySales = Math.floor(Math.random() * 100000) + 50000
      data.conversionRate = (Math.random() * 5 + 2).toFixed(2)
      data.timestamp = Date.now()
    }

    updateData() // 立即更新一次
    timer = setInterval(updateData, interval)
  }

  const stop = () => {
    if (timer) {
      clearInterval(timer)
      timer = null
    }
  }

  return {
    data,
    start,
    stop
  }
}

export default wsManager
